package com.ldkj.panzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ldkj.panzh.param.VehicleQueryParam;
import com.ldkj.panzh.service.VehicleInfoService;
import com.ldkj.panzh.utils.CommentUtils;
import com.ldkj.panzh.vo.VehicleInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 车辆信息服务实现类
 *
 * @author qiancheng
 * @date 2025-11-19
 */
@Slf4j
@Service
public class VehicleInfoServiceImpl implements VehicleInfoService {

    // API网关相关常量
    private static final String ARTEMIS_PATH = "/artemis";
    // 车辆列表查询接口
    private static final String GET_VEHICLE_LIST_API = ARTEMIS_PATH + "/api/resource/v2/vehicle/advance/vehicleList";

    // 接口参数常量
    private static final String PAGE_NO = "pageNo";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SUCCESS_CODE = "0";

    @Autowired
    public CommentUtils commentUtils;

    /**
     * 查询车辆列表
     */
    @Override
    public List<VehicleInfoVO> queryVehicleList(VehicleQueryParam vehicleQueryParam) throws Exception {

        //设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                vehicleQueryParam.getAppKey(),
                vehicleQueryParam.getAppSecret(),
                vehicleQueryParam.getHost());

        // 准备基础参数
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put(PAGE_NO, vehicleQueryParam.getPageNo());
        paramMap.put(PAGE_SIZE, vehicleQueryParam.getPageSize());

        // 添加可选参数
        if (vehicleQueryParam.getPlateNo() != null && !vehicleQueryParam.getPlateNo().isEmpty()) {
            paramMap.put("plateNo", vehicleQueryParam.getPlateNo());
        }
        if (vehicleQueryParam.getPersonIds() != null && !vehicleQueryParam.getPersonIds().isEmpty()) {
            paramMap.put("personIds", vehicleQueryParam.getPersonIds());
        }
        if (vehicleQueryParam.getVehicleType() != null) {
            paramMap.put("vehicleType", vehicleQueryParam.getVehicleType());
        }
        if (vehicleQueryParam.getPlateType() != null) {
            paramMap.put("plateType", vehicleQueryParam.getPlateType());
        }
        if (vehicleQueryParam.getIsBandPerson() != null) {
            paramMap.put("isBandPerson", vehicleQueryParam.getIsBandPerson());
        }
        if (vehicleQueryParam.getOrderBy() != null && !vehicleQueryParam.getOrderBy().isEmpty()) {
            paramMap.put("orderBy", vehicleQueryParam.getOrderBy());
        }
        if (vehicleQueryParam.getOrderType() != null && !vehicleQueryParam.getOrderType().isEmpty()) {
            paramMap.put("orderType", vehicleQueryParam.getOrderType());
        }

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_VEHICLE_LIST_API);
        List<VehicleInfoVO> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(paramMap);
            log.info("查询车辆列表请求参数: {}", body);

            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");

            log.info("查询车辆列表响应: {}", response);

            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        resultList = JSON.parseArray(list, VehicleInfoVO.class);
                        
                        // 填充枚举名称
                        fillEnumNames(resultList);
                    }
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                log.error(errorMsg);
                throw new Exception(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = "查询车辆列表失败";
            log.error(errorMsg, e);
            throw new Exception(errorMsg, e);
        }
        return resultList;
    }

    /**
     * 填充枚举名称
     */
    private void fillEnumNames(List<VehicleInfoVO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        for (VehicleInfoVO vo : list) {
            // 车牌类型名称
            if (vo.getPlateType() != null) {
                vo.setPlateTypeName(getPlateTypeName(vo.getPlateType()));
            }
            
            // 车辆类型名称
            if (vo.getVehicleType() != null) {
                vo.setVehicleTypeName(getVehicleTypeName(vo.getVehicleType()));
            }
            
            // 状态名称
            if (vo.getStatus() != null) {
                vo.setStatusName(vo.getStatus() == 0 ? "正常" : "异常");
            }
        }
    }

    /**
     * 获取车牌类型名称
     */
    private String getPlateTypeName(Integer plateType) {
        switch (plateType) {
            case 0: return "蓝牌";
            case 1: return "黄牌";
            case 2: return "白牌";
            case 3: return "黑牌";
            case 4: return "绿牌";
            case 5: return "其他";
            default: return "未知";
        }
    }

    /**
     * 获取车辆类型名称
     */
    private String getVehicleTypeName(Integer vehicleType) {
        switch (vehicleType) {
            case 0: return "客车";
            case 1: return "货车";
            case 2: return "轿车";
            case 3: return "面包车";
            case 4: return "小型车";
            case 5: return "中型车";
            case 6: return "大型车";
            default: return "未知";
        }
    }

    /**
     * 查询车辆统计信息
     */
    @Override
    public Map<String, Object> queryVehicleStats(VehicleQueryParam vehicleQueryParam) throws Exception {
        List<VehicleInfoVO> list = queryVehicleList(vehicleQueryParam);
        return calculateStats(list);
    }

    /**
     * 计算统计信息
     */
    private Map<String, Object> calculateStats(List<VehicleInfoVO> list) {
        Map<String, Object> stats = new HashMap<>(8);
        
        if (list == null || list.isEmpty()) {
            stats.put("totalCount", 0);
            stats.put("normalCount", 0);
            stats.put("abnormalCount", 0);
            stats.put("bandPersonCount", 0);
            stats.put("plateTypeStats", new HashMap<>());
            stats.put("vehicleTypeStats", new HashMap<>());
            return stats;
        }

        // 总数
        stats.put("totalCount", list.size());

        // 正常/异常统计
        long normalCount = list.stream().filter(v -> v.getStatus() != null && v.getStatus() == 0).count();
        long abnormalCount = list.stream().filter(v -> v.getStatus() != null && v.getStatus() == 1).count();
        stats.put("normalCount", normalCount);
        stats.put("abnormalCount", abnormalCount);

        // 关联人员统计
        long bandPersonCount = list.stream().filter(v -> v.getIsBandPerson() != null && v.getIsBandPerson() == 1).count();
        stats.put("bandPersonCount", bandPersonCount);

        // 车牌类型统计
        Map<String, Long> plateTypeStats = new HashMap<>();
        for (VehicleInfoVO vo : list) {
            if (vo.getPlateTypeName() != null) {
                plateTypeStats.merge(vo.getPlateTypeName(), 1L, Long::sum);
            }
        }
        stats.put("plateTypeStats", plateTypeStats);

        // 车辆类型统计
        Map<String, Long> vehicleTypeStats = new HashMap<>();
        for (VehicleInfoVO vo : list) {
            if (vo.getVehicleTypeName() != null) {
                vehicleTypeStats.merge(vo.getVehicleTypeName(), 1L, Long::sum);
            }
        }
        stats.put("vehicleTypeStats", vehicleTypeStats);

        return stats;
    }
}
